-- UIBishop
-- Created by cheny3 Sep/08/2016
-- 主教塞缪尔主界面

require "game/ui/form/dungeon/special/UIBishopEquip"

UIBishop = class("UIBishop", function()
    return cc.Layer:create();
end);

function UIBishop.create()
    return UIBishop.new();
end

-- 技能列表
local skillList = {};

-- 模型缩放比例
local MODEL_SCALE = 1.2;

-- 光效缩放比例
local EFFECT_SCALE = 1.5;

function UIBishop:ctor()
    -- 初始化
    self:setName("UIBishop");
    -- 复用海怪船长模板
    local node = cc.CSLoader:createNode("layout/dungeon/special/MonsterCaptain.csb");
    self:addChild(node);
    self.node = node;

	self.bishop = ME.user.bishop;
    skillList = BishopM.query(self.bishop.classId, "skills");
    table.sort(skillList);

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化窗口
    self:initForm();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 部分控件位置修正
function UIBishop:fixPos(desc1, desc2, nameLabel)
    -- desc1的Y轴位置
    local positionY = desc1:getPositionY();

    -- desc1文本控件的高度
    local labelHeight = getRealContentSize(desc1).height;

    -- 设置desc2的位置
    desc2:setPositionY(positionY - labelHeight - 6);

    local labelHeight2 = getRealContentSize(desc2).height;

    local nameHeight = getRealContentSize(nameLabel).height;

    local tipBg = findChildByName(self.node, "CT/tip_bg");
    local totalHeight = nameHeight + labelHeight + labelHeight2 + 50;

    if tipBg.initSize == nil then
        tipBg.initSize = tipBg:getContentSize();
    end

    -- 适配高度（不能超出背景，固定加20）
    if totalHeight >  tipBg.initSize.height then
        tipBg:setContentSize(tipBg.initSize.width, tipBg.initSize.height + 20);
    end
end

-- 适配
function UIBishop:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIBishop:registerEventCallback()
    -- 关注升级后的事件
    EventMgr.register("UIBishop", event.BISHOP_SKILL_UPGRADE, function(args)
        self:redrawAttrib();
    end);

    -- 关注复活后事件
    EventMgr.register("UIBishop", event.BISHOP_REVIVE, function(args)
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIBishop");
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIBishop 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UIBishop");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 注册点击事件
function UIBishop:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIBishop");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 复活按钮
    local btnRevive = findChildByName(self.node, "BT/btn_revive");
    local function onReviveClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            local ret = BishopM.canRevive();
            if true == ret then
                DungeonActionM.go("bishop_revive");
            elseif "cost_lack" then
                local classId = table.keys(FormulaM.invoke("CALC_BISHOP_COST", "revive", self.bishop.classId))[1];
                local name = ItemM.query(classId, "name");
                alert(string.format(getLocStr("item_not_enough2"), name));
            end
        end
    end

    -- 死亡情况下才可以点击
    if self.bishop:isDead() then
        btnRevive:setTouchEnabled(true);
        btnRevive:setBright(true);
    else
        btnRevive:setTouchEnabled(false);
        btnRevive:setBright(false);
    end
    btnRevive:setVisible(true);
    btnRevive:addTouchEventListener(onReviveClick);
    TextStyleM.setTextStyle(btnRevive, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnRevive:setTitleText(getLocStr("btn_text_revive"));
end

-- 初始化窗口
function UIBishop:initForm()
    local panel = findChildByName(self.node, "CT/panel");
    self.panel = panel;

    local panelWidth  = panel:getContentSize().width;
    local panelHeight = panel:getContentSize().height;

    local posY = panelHeight/2;

    local iconWidth  = 94;
    local iconHeight = 94;

    -- 图标与图标直接的间距
    local gap = 25;

    -- 左间距
    local leftWap = 20;

    for i = 1, #skillList do
        -- 复用魔藤技能控件
        local child = cc.CSLoader:createNode("layout/bine/SkillIcon.csb");
        child:setName("item" .. i);
        local posX = iconWidth / 2 + (i - 1)*(iconWidth + gap) + leftWap;
        child:setPosition(posX, posY);
        panel:addChild(child);

        -- 注册框点击事件
        local frameImage = findChildByName(child, "frame");
        frameImage:setTouchEnabled(true);
        local function onFrameClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");

                -- 打开装备介绍界面
                local uiForm = UIBishopEquip.create(skillList[i], self.bishop:getPos(), i);
                UIMgr.getCurrentScene():addForm(uiForm);
            end
        end
        frameImage:addTouchEventListener(onFrameClick);
    end

    -- 初始化光效节点
    local effectNode  = findChildByName(self.node, "CT/left_part/effect_node");
    local effectNode2 = findChildByName(self.node, "CT/left_part/effect_node2");
    effectNode:setScale(EFFECT_SCALE);
    effectNode2:setScale(EFFECT_SCALE);
end

-- 重绘
function UIBishop:redraw()
    -- 显示标题
    local name = BishopM.query(self.bishop.classId, "name");
    local titleLabel = findChildByName(self.node, "CT/bg1/bg/title_label");
    titleLabel:setString(name);
    TextStyleM.setArtWordTitleStyle(titleLabel);

	-- 显示名字和介绍
    local nameLabel = findChildByName(self.node, "CT/monster_name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(name);

    local descLabel = findChildByName(self.node, "CT/monster_desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    local desc = BishopM.query(self.bishop.classId, "desc");
    descLabel:setString(desc["desc1"]);

    local descLabel2 = findChildByName(self.node, "CT/monster_desc2");
    TextStyleM.setTextStyle(descLabel2, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN, false, -1);
    descLabel2:setString(desc["desc2"]);

    self:fixPos(descLabel, descLabel2, nameLabel);

    -- 显示召唤兽模型
    self:createSummonDisplay();

    -- 显示召唤兽属性
    self:redrawAttrib();

    -- 显示召唤兽装备
    self:redrawPanel();
end

-- 显示召唤兽属性
function UIBishop:redrawAttrib()
    local valueLabel, nameLabel;
    local rightPart = findChildByName(self.node, "CT/bg1/right_part");

    local attack = self.bishop:getAttack();
    local magic  = self.bishop:getMagic();
    local maxMp  = self.bishop:getMaxMp();
    local maxHp  = self.bishop:getMaxHp();

    -- 攻击
    nameLabel = findChildByName(rightPart, "attack_node/name");
    valueLabel= findChildByName(rightPart, "attack_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("attack"));
    valueLabel:setString(tostring(attack));

    -- 生命
    local nameLabel= findChildByName(rightPart, "hp_node/name");
    local valueLabel= findChildByName(rightPart, "hp_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("hp"));
    local curHp = math.max(0, self.bishop:getHp());
    local hpstr = string.format(getLocStr("attrib_value_format"), curHp, maxHp);
    valueLabel:setString(hpstr);

    -- 魔力
    local nameLabel= findChildByName(rightPart, "dodge_node/name");
    local valueLabel= findChildByName(rightPart, "dodge_node/value");
    local iconImg = findChildByName(rightPart, "dodge_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("magic"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("magic"));
    valueLabel:setString(tostring(magic));

    -- 魔法
    local nameLabel= findChildByName(rightPart, "accuracy_node/name");
    local valueLabel= findChildByName(rightPart, "accuracy_node/value");
    local iconImg = findChildByName(rightPart, "accuracy_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("mp"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("mp"));
    local curMp = math.max(0, self.bishop:getMp());
    local mpstr = string.format(getLocStr("attrib_value_format"), curMp, maxMp);
    valueLabel:setString(mpstr);
end

-- 是否已经学习技能
function UIBishop:isLearn(skillId)
    return self.bishop:ownSkill(skillId);
end

-- 显示召唤兽技能
function UIBishop:redrawPanel()
    self.iconImgList = {};
    for i = 1, #skillList do
        local child    = findChildByName(self.panel, "item" .. i);
        local iconImg  = findChildByName(child, "icon");
        local starNode = findChildByName(child, "star_node");
        local frame    = findChildByName(child, "frame");
        local text     = findChildByName(child, "text");
        TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_ORANGE, true);

        table.insert(self.iconImgList, iconImg);

        local skillId = skillList[i];
        local itemId = BishopM.getCostItem(skillId);

        -- 绘制图标
        iconImg:loadTexture(getItemIconPath(ItemM.query(itemId, "icon")));
        if not iconImg.oriScale then
            iconImg.oriScale = iconImg:getScale();
        end

        setGrayMode(iconImg, false);

        -- 如果该装备已装上
        if self:isLearn(skillId) then
            setGrayMode(iconImg, false);
            frame:setOpacity(255);
            text:setVisible(true);
            text:setString(string.format(getLocStr("level_format"),
                self.bishop:getSkillLevel(skillId)));
        else
            -- 灰化处理
            setGrayMode(iconImg, true);
            -- 框需要半透明
            frame:setOpacity(100);
            text:setVisible(false);
        end

        if true == BishopM.canLearnSkill(skillId)
            or true == BishopM.canUpgradeSkill(skillId) then
            -- 可穿戴，播放气泡动画
            playBubbleAnima(iconImg, false);
        else
            iconImg:stopAllActions();
            iconImg:setScale(iconImg.oriScale);
        end
    end
end

-- 创建模型
function UIBishop:createSummonDisplay()
    local classId = self.bishop.classId;
    local monsterNode = findChildByName(self.node, "CT/left_part/model_node");
    if monsterNode.summonDisplay then
        -- 先移除旧模型
        monsterNode:removeChild(monsterNode.summonDisplay);
    end

    -- 创建模型
    local summonId = BishopM.query(classId, "summon_display")
    local summonDisplay = SummonDisplay.create(summonId);

    -- 设置缩放比例
    local scale = SummonM.query(summonId, "model_scale");
    summonDisplay:setScale(scale * 1.5);

    -- 设置偏移量
    local offsetX = -100;
    local offsetY = SummonM.query(summonId, "offset_y") or 0;
    summonDisplay:setPosition(tonumber(offsetX), tonumber(offsetY));

    monsterNode:addChild(summonDisplay);
end

-- 装备成功
function UIBishop:onSubmit(index)
    -- 重绘装备格
    self:redraw();

    -- 播放金属闪过的光效
    playEffect(self.iconImgList[index], 1186, 45, 45);

    -- 更新格子上的血量和攻击
    local pos = BishopM.getBishopPos();
    local grid = UIDungeonMgr.getCurLevel():getAllGrids()[pos];
    grid:updateSummonHPAndAttack();
end